package com.hhw.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FileDownload {
	//匹配的是href中的download请求
	@RequestMapping(value="/download",method=RequestMethod.GET) 
	public ResponseEntity<byte[]> download(HttpServletRequest request,
			@RequestParam("filename") String filename,
			Model model) throws IOException{
		//从我们的上传文件夹中去取
		//String downloadFilePath="D:\\userUploadFile\\Files";
		 String path=request.getServletContext().getRealPath("/images");
		//新建一个文件
		File file = new File(path+File.separator+filename);
		//http头信息
		HttpHeaders headers = new HttpHeaders();
		//设置编码
		String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");

		headers.setContentDispositionFormData("attachment", downloadFileName);
		
		 //application/octet-stream:二进制流数据（常见的文件下载）
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

		//MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息
	    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
			 headers,HttpStatus.CREATED);

	}
}





